package com.system.connect.springboot_flowers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.connect.springboot_flowers.dto.FormDto;
import com.system.connect.springboot_flowers.entity.Originalposts;
import com.system.connect.springboot_flowers.mapper.OriginalpostsMapper;
import com.system.connect.springboot_flowers.service.IOriginalpostsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 原创帖子表 服务实现类
 * </p>
 *
 * @author yang
 * @since 2025-01-16
 */
@Service
public class OriginalpostsServiceImpl extends ServiceImpl<OriginalpostsMapper, Originalposts> implements IOriginalpostsService {

    /**
     * 帖子存入数据库
     * @param formDto
     */
    @Override
    public Boolean create(FormDto formDto) {
        try{
            Originalposts originalposts = new Originalposts();
            originalposts.setUserId(1);
            originalposts.setTiele(formDto.getTitle());
            originalposts.setContent(formDto.getMainboby());
            originalposts.setCategory(formDto.getCategory());
            originalposts.setAnonymity(formDto.getAnonymity());
            originalposts.setType(formDto.getRange());
            save(originalposts);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    
    /**
     * 获取各分类的帖子数量统计
     * @return 分类统计数据列表，每个元素包含分类名称和帖子数量
     */
    @Override
    public List<Map<String, Object>> getCategoryCount() {
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 查询未删除的有效帖子
        QueryWrapper<Originalposts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", false);
        queryWrapper.select("category, count(*) as count");
        queryWrapper.groupBy("category");
        
        // 执行统计查询
        List<Map<String, Object>> stats = baseMapper.selectMaps(queryWrapper);
        
        // 格式化结果
        for (Map<String, Object> stat : stats) {
            Map<String, Object> item = new HashMap<>();
            item.put("category", stat.get("category"));
            item.put("count", stat.get("count"));
            result.add(item);
        }
        
        return result;
    }
}
